<template>
    <div class="SingleChoice">
        <div class="boxForm">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <!-- <el-form-item label="年级：" prop="gradeName">
                    <el-select v-model="ruleForm.gradeName" placeholder="请选择年级">
                        <el-option label="区域一" value="shanghai">1</el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="学科：" prop="subject">
                    <el-select v-model="ruleForm.subject" placeholder="请选择学科">
                        <el-option label="区域一" value="shanghai">1</el-option>
                    </el-select>
                </el-form-item> -->

                <el-form-item label="题干：" prop="questionsStems">
                    <el-upload
                        class="avatar-uploader"
                        ref="avatar"
                        :action="upImg"
                        name="file"
                        :headers="header"
                        :show-file-list="false"
                        :on-success="uploadSuccess"
                        :on-error="uploadError"
                        :before-upload="beforeUpload"
                    >
                    </el-upload>
                    <quill-editor 
                        ref="myQuillEditor" 
                        :options="editorOption"
                        v-model="ruleForm.questionsStems"
                    >
                    </quill-editor>
                </el-form-item>

                <el-form-item label="选项" prop="options">
                  <el-button class="addSelect" @click="addSelect">添加选项</el-button>
                    <div class="boxOption">
                        <div class="opitonsA" v-for="(item,ind) in ruleForm.options" :key="ind" >
                            <p class="option">{{arr[ind]}}</p>
                            <div class="editor">
                                <el-upload
                                    :data-index="ind"
                                    :class="`avatar-uploader${ind}`"
                                    ref="avatar"
                                    :action="upImg"
                                    name="file"
                                    :show-file-list="false"
                                    :headers="header"
                                    :on-success="
                                        (response, file, fileList) =>
                                        uploadSuccess1(response, file, fileList)
                                    "
                                    :before-upload="(response) => changess(response, ind)"
                                    >
                                </el-upload>
                                <div
                                    :data-index="ind"
                                    
                                    style="position: relative"
                                    >
                                    <span
                                        :data-index="ind"
                                        style="
                                            position: absolute;
                                            z-index: 999;
                                            width: 22px;
                                            height: 22px;
                                            top: 20px;
                                            left: 12px;
                                            cursor: pointer;
                                            
                                        "
                                        @click="imgClick"
                                    ></span>
                                    <quill-editor
                                        :data-index="ind"
                                        :options="editorOption1"
                                        v-model="item.optionsName"
                                        :ref="`QuillEditor${ind}`"
                                    >
                                    </quill-editor>
                                </div>
                            </div>
                            <i class="el-icon-delete-solid remove"  @click="removeOptionItem(index)"></i>
                        </div>
                    </div>
                </el-form-item>

                <el-form-item label="标答：" prop="answerNofixed">
                    <el-radio-group v-model="ruleForm.answerNofixed">
                        <el-radio v-for="(item,index) in ruleForm.options" :key="index"
                         :value="ruleForm.answerFixed"
                         :label="arr[index]"
                         @change="radiusChange"
                        ></el-radio>

                    </el-radio-group>
                </el-form-item>
                <el-form-item label="解析：" prop="parse">
                    <el-input v-model="ruleForm.parse"></el-input>
                </el-form-item>
                <el-form-item label="分数：" prop="grades">
                    <el-input-number v-model="ruleForm.grades" @change="handleChange" :min="0" :max="10" label="描述文字"></el-input-number>
                </el-form-item>
                <el-form-item label="难度：" prop="difficulty">
                    <el-rate v-model="ruleForm.difficulty"></el-rate>
                </el-form-item>
                <el-form-item label="知识点：" prop="knowledgePoints">
                    <el-input v-model="ruleForm.knowledgePoint"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
                    <el-button @click="resetForm('ruleForm')">重置</el-button>
                    
                    <el-button @click="preview">预览</el-button>
                    <el-button @click="preservationAdd('ruleForm')">保存并继续添加</el-button>
                    <el-button @click="goBack()">返回</el-button>
                </el-form-item>
            </el-form>
        </div>
        <!-- <div class="dialog"> -->
            <!-- 添加弹框 -->
            <el-dialog
                title="预览"
                :visible.sync="dialogFormVisible"
                width="700"
                height="400"
            >
                <div class="infoDialog">
                    <div class="grade">
                        <div class="gradeBox">
                            <p class="infoGreade">年级：</p>
                            <p class="infoGreade">{{gradeName.length ? gradeName[0].typeName : ''}}</p>
                        </div>
                        <div class="subject">
                            <p>学科：</p>
                            <p>{{subjectName.length ? subjectName[0].courseName : ''}}</p>
                        </div>
                    </div>
                    <div class="testQuestions">
                        <p>试题类型：</p>
                        <p></p>
                    </div>
                    <div class="stem">
                        <p>题干：</p>
                        <p>{{ruleForm.questionsStems}}</p>
                    </div>
                    <div class="selections">
                        <p>选项：</p>
                        <ul class="infoOptions">
                            <li v-for="(item,index) in ruleForm.options" :key="index">
                                <span>{{item.content}}：</span>
                                <span>{{removeHtmlStyle(item.optionsName)}}</span>
                            </li>
                        </ul>
                    </div>
                    <div class="bidAnswers">
                        <p>标答：</p>
                        <p>{{ruleForm.answerNofixed}}</p>
                    </div>
                    <div class="analysis">
                        <p>解析：</p>
                        <p>{{ruleForm.parse}}</p>
                    </div>
                    <div class="fraction">
                        <p>分数：</p>
                        <p>{{ruleForm.grades}}</p>
                    </div>
                    <div class="difficulty">
                        <p>难度：</p>
                        <p>{{ruleForm.difficulty}}</p>
                    </div>
                    <div class="Knowledge">
                        <p>知识点：</p>
                        <p>{{ruleForm.knowledgePoint}}</p>
                    </div>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button class="cancel" @click="cancel"
                        >取 消</el-button
                    >
                    <el-button class="determine" type="primary" @click="sureBtn"
                        >确 定</el-button
                    >
                </div>
            </el-dialog>
        <!-- </div> -->
    </div>
</template>

<script>
import {
    addQuertionBankApi,
    EditQuertionBankApi,
    getGradeListApi,
    // getCourseListApi,
    getQuertionBankListApi,
    upLoadImgApi

} from "@/api/onlinehomework/questionbank.js"
import {HOST} from "@/global.js"
import { getToken } from "@/utils/auth";

const toolbarOptions = [
  ["image"], // 链接、图片、视频-----['link', 'image', 'video']
]
const toolbarOptions1 = [
  ["image"], // 链接、图片、视频-----['link', 'image', 'video']
]
export default {
    name:'SingleChoice',
    props:['gradeId','subjectId','selectIndex'],

    data() {
        var checkAge = (rule, value, callback) => {
             console.log(rule,'----');
            if (!value) {
                return callback(new Error('不能为空'));
            }
            setTimeout(() => {
                if (!Number.isInteger(Number(value))) {
                    callback(new Error('请输入数字值'));
                }
            }, 1000);
            return callback()
        };
        var checkGr = (rule, value, callback) => {
            //  console.log(rule,value,'-----');
            if (!value) {
                return callback(new Error('请选择难度'));
            }
            return callback()

        }
        var checkOptions = (rule, value, callback) => {
            console.log(rule,value,'-----');
            if (value.length <= 0) {
                return callback(new Error('请添加选项'));
            }
            return callback();

        }
        return {
            ruleForm: {
                // gradeName: '', // 年级名称
                // subject: '', // 学科
                questionsStems: '', // 题干
                answerNofixed: '', // 标答
                parse: '', //  解析
                grades: '', // 分数
                difficulty: 0, // 难度
                knowledgePoint: '', // 知识点
                options:[
                  {
                    content:"A",
                    optionsName:''
                  }
                ],
                // resource: ''
            },
            header: {
                Authorization: `Bearer ${getToken()}`,
            },
            editorOption: {
                placeholder: "请在这里输入",
                theme: "snow", //主题 snow/bubble
                modules: {
                history: {
                    delay: 1000,
                    maxStack: 50,
                    userOnly: false,
                },
                toolbar: {
                        container: toolbarOptions,
                        handlers: {
                            image: function (value) {   
                                if (value) {
                                    console.log(value);
                                    // 调用element的图片上传组件
                                    console.log(this);
                                    console.log(document.querySelector(".avatar-uploader"));
                                    // console.log(document.getElementById("avatar"));
                                    document.querySelector(".avatar-uploader input").click();
                                } else {
                                    this.quill.format("image", false);
                                }
                            },
                            image1: function (value) {   
                                if (value) {
                                    console.log(value);
                                    // 调用element的图片上传组件
                                    console.log(this);
                                    console.log(document.querySelector(".avatar-uploader"));
                                    // console.log(document.getElementById("avatar"));
                                    document.querySelector(".avatar-uploader1 input").click();
                                } else {
                                    this.quill.format("image", false);
                                }
                            },
                        },
                    },
                },
            },
            editorOption1: {
                placeholder: "请在这里输入",
                theme: "snow", //主题 snow/bubble
                modules: {
                history: {
                    delay: 1000,
                    maxStack: 50,
                    userOnly: false,
                },
                toolbar: {
                    container: toolbarOptions1,
                    handlers: {
                        image: function (value) {   
                            if (value) {
                                console.log(value);
                                // 调用element的图片上传组件
                                console.log(this);
                                console.log(document.querySelector(".avatar-uploader1"));
                                // console.log(document.getElementById("avatar"));
                                // document.querySelector(".avatar-uploader1 input").click();
                            } else {
                                this.quill.format("image", false);
                            }
                        },
                        image1: function (value) {   
                            if (value) {
                                console.log(value);
                                // 调用element的图片上传组件
                                console.log(this);
                                console.log(document.querySelector(".avatar-uploader"));
                                // console.log(document.getElementById("avatar"));
                                document.querySelector(".avatar-uploader1 input").click();
                            } else {
                                this.quill.format("image", false);
                            }
                        },
                    },
                },
                },
            },
            rules: {
                grade: [
                    { required: true, message: '请选择年级', trigger: 'blur' },
                ],
                subject: [
                    { required: true, message: '请选择学科', trigger: 'change' }
                ],
                questionsStems: [
                    {  required: true, message: '请输入题干', trigger: 'change' }
                ],
                options: [
                    {  validator: checkOptions, required: true,  trigger: 'blur' }
                ],
                answerNofixed: [
                    { required: true, message: '标准答案', trigger: 'change' }
                ],
                parse: [
                    {  message: '解析', trigger: 'change' }
                ],
                grades: [
                    { validator: checkAge, required: true, trigger: 'change' }
                ],
                difficulty: [
                    {validator: checkGr, required: true,  trigger: 'blur' }
                ],
                knowledgePoint: [
                    {required: true, message: '知识点', trigger: 'change' }
                ],
            },
            arr:['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],
            dialogFormVisible:false, // 弹框开关
            subjectOptions:[],  //  学科
            gradeOptions:[], // 年级
            upImg:`${HOST}/file/upload`,
            uploadIndex:0
        }
    },
    computed:{
        gradeName() {
            return  this.gradeOptions.filter(item=>{
                return item.typeId == this.gradeId
            })
        },
        subjectName() {
            return this.subjectOptions.filter(item=>{
                console.log(item);
                return item.courseTypeId == this.subjectId
            })
        }
    },
    mounted() {
        // console.log(JSON.parse(this.$route.params.row.options));
        console.log(this.$route.params);
        this.$emit('changeIndex', this.$route.params.tabIndex)
        if(this.$route.params.isEdit == '1' && this.$route.params.tabIndex == 0) {
            getQuertionBankListApi({pageSize:'10',pageNum:this.$route.params.currentPage}).then(res=>{
                let filterItem = res.rows.filter(item=>{
                    console.log(item);
                    return item.questionsId == this.$route.params.row
                })
                console.log(filterItem[0]);
                this.ruleForm = filterItem[0]
                // this.ruleForm.options.difficulty = Number(filterItem[0].difficulty)
                this.ruleForm.options = JSON.parse(this.ruleForm.options)
                this.ruleForm.difficulty = Number(this.ruleForm.difficulty)
                console.log('322234',this.ruleForm);
            })
        //     this.ruleForm.options = JSON.parse(this.$route.params.row.options)
        }
        // console.log(this.$route.params);
        getGradeListApi({parentId:55}).then(res=>{
            this.gradeOptions = res.rows
        })

        getGradeListApi({parentId:130}).then(res=>{
            this.subjectOptions = res.rows
        })
    },
    methods:{
        imgClick(e) {
            console.log(e, "-----index");
            this.uploadIndex = e.target.dataset.index
            console.log(
                document.querySelector(`.avatar-uploader${e.target.dataset.index}`)
            );
            
            document
                .querySelector(`.avatar-uploader${e.target.dataset.index} input`)
                .click();
        },
        fileChange1(files) {
            let formData = new FormData(); 
            formData.append('file', files.raw);
            console.log(files,'----change');
            upLoadImgApi(formData).then((res) => {
                console.log(res.data.url);
                // this.imageUrl = res.data.url
                // file.target.url = ''
                // document.getElementsByName
                let quill = this.$refs.myQuillEditor.quill
                // 上传成功所执行
                // if (res.code == 200) {
                    // 获取光标所在位置
                    let length = quill.getSelection().index;
                    // 插入图片res为服务器返回的数据
                    console.log(res);
                    console.log(length);
                    quill.insertEmbed(length, 'image', res.data.url)
                    // 光标移动至文本末端
                    quill.setSelection(length + 1)
                // } else {
                //     this.$message.error('图片插入失败')
                // }
            });
        },
        
        uploadError() {},
        // 上传图片成功返回事件
        uploadSuccess(res) {
            // 获取富文本组件实例
            let quill = this.$refs.myQuillEditor.quill;
            console.log(quill,'-------选项上传');
            // 如果上传成功
            if (res) {
                // 获取光标所在位置
                let length = quill.getSelection().index;
                // 插入图片，res为服务器返回的图片链接地址
                quill.insertEmbed(length, "image", res.data.url);
                // 调整光标到最后
                quill.setSelection(length + 1);
            } else {
                // 提示信息，需引入Message
                this.$message.error("图片插入失败！");
            }
            this.quillUpdateImg = false;
        },
        changess(file,index){
            console.log(file);
            console.log(index);
        },
        uploadSuccess1(res,file,fileList) {
            console.log(res,'res');
            console.log(fileList,'res');
            console.log(file,'file');
            // 获取富文本组件实例
            console.log(this.$refs[`QuillEditor${this.uploadIndex}`]);
            let quill1 = this.$refs[`QuillEditor${this.uploadIndex}`][0].quill;
            console.log(res);
            // // 如果上传成功
            if (res) {
                // 获取光标所在位置
                let length = quill1.getSelection();
                // 插入图片，res为服务器返回的图片链接地址
                quill1.insertEmbed(length, "image", res.data.url);
                // 调整光标到最后
                quill1.setSelection(length + 1);
            } else {
                // 提示信息，需引入Message
                this.$message.error("图片插入失败！");
            }
            // this.quillUpdateImg = false;
        },
        beforeUpload() {},
      


        childMethods(val) {
            console.log(val);
            // getGradeListApi({parentId:55}).then(res=>{
            //     this.gradeOptions = res.rows
            //     let filterItem = this.gradeOptions.filter(item=>{
            //         return item.typeId == val
            //     })
            //     this.
            // })
        },
        // 单选框
        radiusChange(val) {
            console.log(val,'sssss');
            this.ruleForm.answerNofixed = val
        },
        handleChange() {},
        // 提交表单
        submitForm(formName) {
            console.log(this.selectIndex,'---------index');
            this.$emit('submitForm');
            console.log(this.ruleForm.questionsStems);
            this.$refs[formName].validate((valid) => {
                if(this.$route.params.isEdit == '0') {
                    if (valid) {
                        let obj = {
                            questionsStems:this.ruleForm.questionsStems,
                            questionsType:Number(this.selectIndex),
                            answerNofixed:this.ruleForm.answerNofixed,
                            grades:this.ruleForm.grades,
                            difficulty:this.ruleForm.difficulty,
                            knowledgePoint:this.ruleForm.knowledgePoint,
                            parse:this.ruleForm.parse,
                            grade:this.gradeId,
                            subject:this.subjectId,
                            options:this.ruleForm.options
                        }
                        console.log(obj);
                        addQuertionBankApi(obj).then(res=>{
                            console.log(res,'----------->res');
                            if(res.code === 200) {
                                this.$message({
                                    type: 'success',
                                    message: '添加成功',
                                });
                                this.$router.push({
                                    path:"/onlinehomework/questionbank/questionBankList"
                                })
                            }else {
                                this.$message({
                                    type: 'error',
                                    message: '添加失败',
                                });
                            }
                            // this.
                        })
                    }
                }else {
                    console.log(this.$route);
                    let obj = {
                        questionsStems:this.ruleForm.questionsStems,
                        questionsType:Number(this.selectIndex),
                        answerNofixed:this.ruleForm.answerNofixed,
                        grades:this.ruleForm.grades,
                        difficulty:this.ruleForm.difficulty,
                        knowledgePoint:this.ruleForm.knowledgePoint,
                        parse:this.ruleForm.parse,
                        grade:this.gradeId,
                        subject:this.subjectId,
                        options:this.ruleForm.options,
                        questionsId:Number(this.$route.params.row)
                    }
                    EditQuertionBankApi(obj).then(res=>{
                        console.log(res,'------------>');
                        if(res.code === 200) {
                            this.$message({
                                type: 'success',
                                message: '修改成功',
                            });
                            this.$router.push({
                                path:"/onlinehomework/questionbank/questionBankList"
                            })
                        }else {
                            this.$message({
                                type: 'error',
                                message: '修改失败',
                            });
                        }
                    })
                }
            });
        },
        // 返回
        goBack() {
            this.$router.push({
                path:"/onlinehomework/questionbank/questionBankList"
            })
        },
        // 删除选项
        removeOptionItem(index) {
            this.ruleForm.options.splice(index,1)
        },
        // 重置
        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.$emit('resetForm')
        },
        removeHtmlStyle (html) {
            let relStyle = /style\s*?=\s*?([‘"])[\s\S]*?\1/g; //去除样式
            let relTag = /<.+?>/g; //去除标签
            let relClass = /class\s*?=\s*?([‘"])[\s\S]*?\1/g;// 清除类名
            let newHtml = "";
            if (html) {
                newHtml = html.replace(relStyle, "");
                newHtml = newHtml.replace(relTag, '');
                newHtml = newHtml.replace(relClass, '');
            }
            return newHtml;
        },
        // 添加选项
        addSelect() {
            if(this.ruleForm.options.length < 26) {
                this.ruleForm.options.push({content:String.fromCharCode(this.ruleForm.options.length + 65),optionsName:''})
                return console.log(this.ruleForm.options);
            }else {
                alert('没有更多字母了')
            }
            console.log(this.ruleForm.options,'---------->optionsss');
        },
        // 预览
        preview() {
            this.dialogFormVisible = true
            // this.
            console.log(23);
            console.log(this.ruleForm,'--------->预览');
        },
        // 弹框取消确定事件
        cancel() {
            this.dialogFormVisible = false
        },
        sureBtn() {
            this.dialogFormVisible = false
        },
        // 保存并继续添加
        preservationAdd() {
            let obj = {
                questionsStems:this.ruleForm.questionsStems,
                questionsType:Number(this.selectIndex),
                answerNofixed:this.ruleForm.answerNofixed,
                grades:this.ruleForm.grades,
                difficulty:this.ruleForm.difficulty,
                knowledgePoint:this.ruleForm.knowledgePoint,
                parse:this.ruleForm.parse,
                grade:this.gradeId,
                subject:this.subjectId,
                options:this.ruleForm.options
            }
            addQuertionBankApi(obj).then(res=>{
                console.log(res,'----------->res');
                if(res.code === 200) {
                    this.$refs['ruleForm'].resetFields();
                }
            })
        },
    }

}
</script>

<style lang='scss' scoped>
.SingleChoice{
    width: 100%;
    height: 100%;
    min-width: 100vh;
    padding: 0 20px 20px 20px;
    .boxForm{
        width: 100%;
        background-color: #fff;
        // padding: 10px 20px 10px 0;
        // border-radius: 10px;
        .addSelect{
          float: right;
        }
        .boxOption{
            padding: 30px 0;
            .opitonsA,
            .opitonsB,
            .opitonsC,
            .opitonsD{
                display: flex;
                justify-content: space-around;
                margin-top: 10px;
                .option{
                    width: 50px;
                    text-align: center;
                }
                .editor{
                    flex: 1;
                }
                .remove{
                    width: 50px;
                    padding: 10px 0;
                    color: #f56c6c;
                    text-align: center;
                    cursor: pointer;
                }
            }
            .optionA p{
                width: 50px;
            }
        }
        .el-rate{
            line-height: 2.5;
        }
    }
    // .dialog{
    ::v-deep .el-dialog{
        width: 600px;
        height: 560px;
        border-radius: 10px 10px 0 0;
        .el-dialog__header {
            border-radius: 10px 10px 0 0;
            text-align: center;
            background-color: rgb(72, 149, 219);
            .el-dialog__title {
                color: #fff;
            }
            .el-dialog__headerbtn .el-dialog__close {
                color: #fff;
            }
        }
        .dialog-footer {
            text-align: center;
            button {
                width: 100px;
                height: 35px;
                border-radius: 16px;
                line-height: 0;
            }
            .cancel {
                border: none;
                color: #848383;
                background-color: #f0f0f0;
            }
            .determine {
                border: none;
                background-color: #4995dc;
            }
        }
        .infoDialog{
            // width: 700px;
            // height: 500px;
            .grade{
                width: 100%;
                height: 40px;
                .gradeBox{
                    display: flex;
                    p:first-child{
                        width: 80px;
                    }
                }
                .subject{
                    display: flex;
                    p:first-child{
                        width: 80px;
                    }
                }
            }
            .testQuestions,
            .stem,
            .bidAnswers,
            .analysis,
            .fraction,
            .difficulty,
            .Knowledge
            {
                display: flex;
                width: 100%;
                height: 40px;
                align-items: center;
                p:first-child{
                    width: 80px;
                    // text-align: right;
                }
            }
            .selections{
                width: 100%;
                height: 68px;
                display: flex;
                overflow-y: auto;
                // align-items: center;
            }
        }
    }

    // }
}
</style>